import 'package:redux/redux.dart';
import 'package:state_management_redux/contactor/contactor_api.dart';

import 'contactor_action.dart';
import 'contactor_state.dart';

void fetchContactorMiddleware(
    Store<ContactorState> store, action, NextDispatcher next) {
  const int pageSize = 10;
  if (action is RefreshAction) {
    // 刷新取第一页数据
    ContactorService.list(1, pageSize).then((response) {
      if (response != null && response.statusCode == 200) {
        store.dispatch(SuccessAction(response.data, 1));
      } else {
        store.dispatch(FailedAction('请求失败'));
      }
    }).catchError((error, trace) {
      store.dispatch(FailedAction(error.toString()));
    });
  }

  if (action is LoadAction) {
    // 加载更多时页码+1
    int currentPage = store.state.currentPage + 1;
    ContactorService.list(currentPage, pageSize).then((response) {
      if (response != null && response.statusCode == 200) {
        store.dispatch(SuccessAction(response.data, currentPage));
      }
    }).catchError((error, trace) {
      store.dispatch(FailedAction(error.toString()));
    });
  }

  next(action);
}
